package com.wgts.wgts.mvp.view.activity.tasklobby;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hjq.permissions.XXPermissions;
import com.umeng.socialize.utils.Log;
import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.control.dialog.ToastDate;
import com.wgts.wgts.control.dialog.ToastDialogFragment;
import com.wgts.wgts.control.dialog.WonderLoadingDialog;
import com.wgts.wgts.control.eventbus.TaskDetailsEventBus;
import com.wgts.wgts.control.oss.FileUtils;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerSubmitTaskActivityComponent;
import com.wgts.wgts.dagger.module.SubmitTaskActivityModule;
import com.wgts.wgts.mvp.presenter.ISubmitTaskActivityPresenter;
import com.wgts.wgts.mvp.view.ISubmitTaskActivityView;
import com.wgts.wgts.tools.MoHuGlide;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/*
 *
 *
 */
@RuntimePermissions
public class SubmitTaskActivity extends BaseActivity implements ISubmitTaskActivityView {
    @Inject
    ISubmitTaskActivityPresenter presenter;
    @BindView(R.id.back_btn_image)
    ImageView backBtnImage;
    @BindView(R.id.back_btn_ly)
    LinearLayout backBtnLy;
    @BindView(R.id.include_title)
    TextView includeTitle;
    @BindView(R.id.include_text)
    TextView includeText;
    @BindView(R.id.include_right_image)
    ImageView includeRightImage;
    @BindView(R.id.include_right_ly)
    LinearLayout includeRightLy;
    @BindView(R.id.placeholder_image)
    LinearLayout placeholderImage;
    @BindView(R.id.task_image)
    ImageView taskImage;
    @BindView(R.id.submit_task_ly)
    LinearLayout submitTaskLy;
    public static final String ISSUE_TASK_ID = "issueTaskId";
    public static final String ISSUE_TASK_CODE = "issueTaskCode";
    public static final String SUBMIT_TASK_ID = "submitTaskId";
    public static final String TASK_ID = "taskId";
    private Integer issueTaskId, submitTaskId;
    private String issueTaskCode;

    public static final String TYPE = "type";

    private static final String FILE_PATH = "com.wgts.wgts.fileprovider";

    private int REQUEST_CODE_CHOOSE = 1;

    private List<Uri> mSelected;

    private String type;

    private String comeType;

    private Integer taskId;

    private TaskDetailsEventBus eventBus;
    private WonderLoadingDialog dialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wgts_submit_task_activity);
        ButterKnife.bind(this);
        type = getIntent().getStringExtra(TYPE);
        comeType = getIntent().getStringExtra(WgtsTaskDetailsActivity.COME_TYPE);
        initView();
    }

    private void initView() {
        dialog = new WonderLoadingDialog(this);
        eventBus = new TaskDetailsEventBus();
        if (type.equals("issue")){
            issueTaskId = getIntent().getIntExtra(ISSUE_TASK_ID, 0);
            issueTaskCode = getIntent().getStringExtra(ISSUE_TASK_CODE);
            includeTitle.setText("发布广告");
        }else {
            taskId = getIntent().getIntExtra(TASK_ID, 0);
            submitTaskId = getIntent().getIntExtra(SUBMIT_TASK_ID, 0);
            includeTitle.setText("提交任务");
        }
        includeRightLy.setClickable(false);
    }

    @Override
    public void init() {
        DaggerSubmitTaskActivityComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .submitTaskActivityModule(new SubmitTaskActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void onError(int status, String msg) {
        if (dialog != null && dialog.isShowing()){
            dialog.dismiss();
        }
        MoHuToast.showToast(msg);
    }

    @OnClick({R.id.back_btn_ly, R.id.include_right_ly, R.id.placeholder_image, R.id.submit_task_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn_ly:
                finish();
                break;
            case R.id.include_right_ly:
                SubmitTaskActivityPermissionsDispatcher.addIdeaBackImageWithPermissionCheck(this, 1);
                break;
            case R.id.placeholder_image:
                SubmitTaskActivityPermissionsDispatcher.addIdeaBackImageWithPermissionCheck(this, 1);
                break;
            case R.id.submit_task_ly:
                if(mSelected != null && mSelected.size() > 0){
                    if (dialog != null && !dialog.isShowing()){
                        dialog.show();
                    }
                    submitTask();
                }else{
                    MoHuToast.showToast("请选择图片");
                }

                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data ){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = new ArrayList<>();
            for (int i = 0; i < Matisse.obtainResult(data).size(); i++){
                mSelected.add(Matisse.obtainResult(data).get(i));
            }
            MoHuGlide.getInstance().MatchImage(this, mSelected.get(0).toString(), taskImage);
            placeholderImage.setVisibility(View.GONE);
            includeText.setText("重新上传");
            includeRightLy.setClickable(true);
        }
    }


    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void addIdeaBackImage(int size){
        Matisse.from(SubmitTaskActivity.this)
                .choose(MimeType.ofImage(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, FILE_PATH))
                .maxSelectable(size)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .theme(R.style.Matisse_Dracula)
                .imageEngine(new com.wgts.wgts.control.matisse.GlideEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE); // 设置作为标记的请求码
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    public void askAgain(){
        ToastDate toastDate = new ToastDate();
        toastDate.setCancelQuestion("拒绝权限部分功能将不能使用，请去设置打开权限");
        toastDate.setCancelText("去设置");
        toastDate.setPointText("取消");
        toastDate.setFragmentManager(getSupportFragmentManager());
        ToastDialogFragment fragment = ToastDialogFragment.setToastMessage(toastDate);
        fragment.show(getSupportFragmentManager(), "");
        fragment.setOnClickListener(new ToastDialogFragment.OnClickListener() {
            @Override
            public void onClickCancle() {
                MoHuToast.showToast("您已拒绝了相应权限，保存图片失败");
            }

            @Override
            public void onClickEnsuer() {

                XXPermissions.gotoPermissionSettings(SubmitTaskActivity.this);
            }
        });
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void addIdeaBackImageWrong(){
        MoHuToast.showToast("获取权限失败，可能无法上传照片");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SubmitTaskActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    private void submitTask(){
        String filePath = FileUtils.getRealFilePath(SubmitTaskActivity.this, mSelected.get(0));

       presenter.uploadImg(filePath);


    }

    @Override
    public void loadResult(String result) {
        switch (type){
            case "issue":
                presenter.issueTask(issueTaskId, issueTaskCode, result);
                break;
            case "submit":
                presenter.submitTask(taskId, submitTaskId, result);
                break;
        }
    }

    @Override
    public void issueResult(Integer entity) {
        if (dialog != null && dialog.isShowing()){
            dialog.dismiss();
        }
        eventBus.setId(entity);
        MoHuToast.showToast("发布成功");
        finish();
        EventBus.getDefault().post(eventBus);
    }

    @Override
    public void submitResult(Integer entity) {
        if (dialog != null && dialog.isShowing()){
            dialog.dismiss();
        }
        eventBus.setId(entity);
        MoHuToast.showToast("提交成功");
        finish();
        EventBus.getDefault().post(eventBus);
    }

    @Override
    public void finish(){
        super.finish();
        if(dialog!=null){
            if(dialog.isShowing()){
                dialog.dismiss();
                dialog = null;
            }
        }
    }
}
